const { firefox } = require('playwright');
const { initConfig } = require('./config')
const chalk = require('chalk')

module.exports = async (res) => {
  console.log(chalk.red('请不要操作弹出的浏览器'))
  const browser = await firefox.launch({
    headless: true,
    // args: [`--window-size=1440,900`]
  });
  const page = await browser.newPage();
  await page.setDefaultTimeout(30000)
  await page.goto('https://www.cugbonline.cn:8443/cas/', {
    waitUntil: 'networkidle',
  });

  // 登录
  console.log('开始登录')
  await page.type('#username', res.username, { delay: 0 })
  await page.type('#password', res.password, { delay: 0 })
  await Promise.all([
    // page.waitForNavigation({
    //   waitUntil: 'domcontentloaded'
    // }),
    page.click('.btn-submit'),
  ]);

  await page.waitForNavigation({
    waitUntil: 'domcontentloaded'
  })

  const frame = page.frames().find((frame) => frame.name() === 'main');
  if (!frame) {
    console.log(chalk.red('登录失败，账号密码错误，请退出重新登录'))
    await browser.close();
  }

  const user = await frame.$$eval('.userinfobody li', (element) => {
    const userInfo = {}
    element.forEach((item, index) => {
      userInfo[index] = item.textContent.replace(/\s/g, '').match(/：(\S*)/)?.[1];
    })
    return userInfo
  });

  console.log(chalk.green('登录成功：'))
  console.log('姓名', user[0])
  console.log('在线总时长', user[2])
  console.log('登录次数', user[3])
  console.log()

  let curriculum = await frame.$$eval('.list.clearfix a', (element) => {
    return element.map((item, index) => {
      return {
        name: item.textContent.replace(/\s/g, ''),
        href: item.href
      }
    })
  })

  initConfig({ ...res, classList: curriculum.map(item => item.name) })

  console.log('没有待处理的任务了，关闭浏览器')
  await browser.close();

}